<?php


require_once(dirname(__FILE__).'/../common/log.php');


class HttpUtils
{
    private static function make_header($data)
    {
        $arr  = [];
        foreach ($data as $k => $v)
        {
            $arr[]  = "$k: $v";
        }

        return $arr;
    }

    public static function send_get_request($url, $head = [], $param = [])
    {
        //初始化
        $ch   = curl_init();

        //参数
        if (!empty(param))
        {
            foreach ($param as $key => $val)
            {
                $str[]  = $key."=".$val;
            }

            $url  = $url."?".join('&', $str);
        }

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, 0);

        //http头
        if (!empty($head))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, HttpUtils::make_header($head));
        }

        //执行并获取结果
        $ret['code']  = curl_errno($ch);
        $ret['info']  = curl_getinfo($ch);
        $ret['data']  = curl_exec($ch);
        $ret['hint']  = curl_error($ch);
       
        //释放curl句柄
        curl_close($ch);

        return $ret;
    }

    public static function send_post_request($url, $head = [], $body = [])
    {
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, 1);

        //http头
        if (!empty($head))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, HttpUtils::make_header($head));
        }
        
        //post数据
        if (!empty($body))
        {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }

        //执行并获取结果
        $ret['code']  = curl_errno($ch);
        $ret['info']  = curl_getinfo($ch);
        $ret['data']  = curl_exec($ch);
        $ret['hint']  = curl_error($ch);

        //释放curl句柄
        curl_close($ch);

        return $ret;
    }
}

